package com.vvv.designpattern.service.decorator;

import com.vvv.designpattern.pojo.Order;
import com.vvv.designpattern.pojo.Products;
import com.vvv.designpattern.repo.ProductsRepository;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author vvv
 * @date 2023-11-24 16 46
 * discription装饰器模式：OrderServiceDecorator为具体装饰角色，
 * decoratorPay就是在已有对象的逻辑的基础上增加新的装饰方法（updateScoreAndSendRedPaper）
 */
@Service
public class OrderServiceDecorator extends AbstractOrderServiceDecorator {

    @Value("${delay.service.time}")
    private String delayServiceTime;

    @Resource
    private ProductsRepository productsRepository;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    protected void updateScoreAndSendRedPaper(String productId, int serviceLevel, float price) {
        switch (serviceLevel) {
            case 0:
                // 正常服务
                int score = Math.round(price) / 100;
                System.out.println("正常处理，为用户更新积分！ score = " + score);
                Products product = productsRepository.findByProductId(productId);
                if (product != null && product.getSendRegBag() == '1') {
                    System.out.println("正常处理，为用户发放红包！ productId = " + productId);
                }
                // 模拟操作数据库和发红包
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                break;
            case 1:
                // 延时处理
                Message message = MessageBuilder
                        .withBody(productId.getBytes()).setExpiration(delayServiceTime).build();
                rabbitTemplate.send("normalExchange", "myRkey", message);
                System.out.println("延时处理，时间 = " + delayServiceTime);
                break;
            case 2:
                System.out.println("暂停服务! ");
                break;
            default:
                throw new UnsupportedOperationException("不支持的服务器级别 ！");
        }
    }

    public Order decoratorPay(String orderId, int serviceLevel, float price) {
        Order order = super.pay(orderId);

        try {
            this.updateScoreAndSendRedPaper(order.getProductId(), serviceLevel, price);
        } catch (Exception e) {
           // 重试
        }
        return order;
    }
}
